package mrms.api.web.controllers;

import mrms.api.entity.UserEntity;
import mrms.api.web.utils.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lenchu
 * @date 2019/02/16
 */
@RestController
public class UploadAndDownloadController {
    @Value("${app.io.fileUploadPath:upload/}")
    private String path;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile multipartFile,
                             @RequestAttribute UserEntity user) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();

        String newPath = path + user.getId() + "/";
        
        File dest = new File(newPath + originalFilename);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        
        IOUtils.copy(multipartFile.getInputStream(), new FileOutputStream(dest));

        Map<String, Object> map = new HashMap<>(4);
        map.put("path", newPath);
        map.put("name", originalFilename);
        map.put("originalFilename", originalFilename);

        return Result.success(map);
    }

    @GetMapping("/download")
    public InputStreamResource download(@RequestParam String path,
                                        @RequestParam String name,
                                        HttpServletResponse response) throws FileNotFoundException {
        File f = new File(path + "/" + name);
        response.setHeader("content-disposition", "attachment;filename=" + f.getName());
        return new InputStreamResource(new FileInputStream(f));
    }
}
